package com.js.auth.client.runner;

import com.js.auth.client.config.ServiceAuthConfig;
import com.js.auth.client.config.UserAuthConfig;
import com.js.auth.client.feign.ServiceAuthFeign;
import com.js.common.response.BaseResponse;
import com.js.common.response.ObjectRestResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;

/**
 * @author ygl
 * @create 2018-10-30
 * @DESCRIPTION
 * 认证客户端启动时执行以下操作：
 * 1。 刷新获取公钥
 **/
@Slf4j
@Configuration
public class AuthClientRunner implements CommandLineRunner {

    @Autowired
    private ServiceAuthConfig serviceAuthConfig;
    @Autowired
    private UserAuthConfig userAuthConfig;
    @Autowired
    private ServiceAuthFeign serviceAuthFeign;

    /**
     * 需要认证的客户端服务启动时，需要向认证服务器申请解密token的公钥。存在userAuthConfig中
     * @param args
     * @throws Exception
     */
    @Override
    public void run(String... args) throws Exception {
        try {
            refreshUserPubKey();
            log.info("*********************完成初始化加载用户公钥******************");
        }catch(Exception e){
            log.error("初始化加载用户pubKey失败,请检查auth服务是否正常启动,1分钟后自动重试!",e);
        }
    }

    public void refreshUserPubKey(){
        BaseResponse resp = serviceAuthFeign.getUserPublicKey(serviceAuthConfig.getClientId(), serviceAuthConfig.getClientSecret());
        if (resp.getStatus() == HttpStatus.OK.value()) {
            ObjectRestResponse<byte[]> userResponse = (ObjectRestResponse<byte[]>) resp;
            this.userAuthConfig.setPubKeyByte(userResponse.getData());
        }
    }
}
